package com.rimi.util;

import com.alibaba.fastjson.JSONObject;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.rimi.model.dto.LoginDto;

import java.text.ParseException;
import java.util.Date;

/**
 * @author liHaiYang
 * @version V1.0
 * @Description: (用一句话描述该文件做什么)
 * @date 2021/7/2 14:41
 */
public class JwtUtil {

    private static String key = "jbgoifejgiojnbnfnvinvnvnrvnvonrbndwijncdw";

    //加密
    public static String encode(Object data) throws JOSEException {

        //创建基于HS256加密算法的header
        JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.HS256);

        //创建PayLoad
        Payload payload = new Payload(JSONObject.toJSONString(data));

        //创建JWS签名对象,绑定秘钥
        JWSSigner signer = new MACSigner(key);
        //创建JWS对象
        JWSObject jwsObject = new JWSObject(jwsHeader,payload);

        //对JWS对象进行签名
        jwsObject.sign(signer);
        return jwsObject.serialize();
    }

    public static <T> T decode(Class<T> clazz,String decode) throws JOSEException, ParseException {

        //解析加密的字符串
        JWSObject parse = JWSObject.parse(decode);

        //被加密的载体
        Payload payload = parse.getPayload();

        //创建验签对象
        MACVerifier macVerifier = new MACVerifier(key);

        //验证签名
        if(parse.verify(macVerifier)){
            //验证签名成功

            //以json字符串获取数据
            String string = payload.toString();
            //将json字符串转换为java对象
            return JSONObject.parseObject(string,clazz);
        }
        throw new JOSEException("验签失败");
    }

    public static void main(String[] args) throws JOSEException, ParseException {
        LoginDto loginDto = new LoginDto();
        loginDto.setId(1);
        loginDto.setExp(new Date());

        String encode = encode(loginDto);
        System.out.println(encode);

        LoginDto decode = decode(LoginDto.class,encode);
        System.out.println(decode);

    }
}
